package com.shimao.celnet.payment.controller;

import com.baiwang.bop.request.impl.invoice.common.InvoiceDetails;
import com.baiwang.bop.request.impl.invoice.common.InvoiceMainInfo;
import com.baiwang.bop.respose.entity.InvoiceQueryResponse;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invoiceQueryOutController;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.model.PInvoiceRed;
import com.shimao.celnet.payment.model.request.CallIn_newOutInvOpenBuleReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import io.swagger.annotations.Api;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import javax.validation.Valid;
import java.util.List;

/**
 *
 * 外部系统--》支付系统 数据：发票查询数据
 * 发票查询接口
 * Created by Galen on 2018/12/4.
 */
@RestController
@RequestMapping(value = "/invoice")
@Api("接口：inv-166-外部发票查询请求<OutInvQueryReqIn> 外部系统 → 支付系统，数据：发票查询数据")
public class CallIn_OutInvQueryReqInController {

    protected Logger logger = Logger.getLogger(this.getClass());
    /*** 蓝票*/
    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;
    /*** 红票*/
    @Autowired
    private PInvoiceRedService pInvoiceRedService;
    @Autowired
    private CallOut_invoiceQueryOutController callOut_invoiceQueryOutController;

    @RequestMapping(value = "/invoiceQueryReq",method = RequestMethod.POST)
    public String invQueryReq(@RequestBody @Valid CallIn_newOutInvOpenBuleReqIn requestJson, BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("inv-166-外部发票查询请求<OutInvQueryReqIn>请求JSON:" + requestJson.toString());
        if (requestJson.getInvoiceType() == null || "".equals(requestJson.getInvoiceType())){
            retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS,"invoiceType");
        }
        if(requestJson.getInvoiceCode() == null || "".equals(requestJson.getInvoiceCode())){
            retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS,"invoiceCode");
        }
        if(requestJson.getInvoiceNo() == null || "".equals(requestJson.getInvoiceNo())){
            retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS,"invoiceNo");
        }
        if (requestJson.getReceiptGuid() == null || "".equals(requestJson.getReceiptGuid())){
            retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS,"receiptGuid");
        }
        // 请求百望进行发票查询，2发票号码和发票代码查询
        InvoiceQueryResponse response = null;
        if ("0".equals(requestJson.getInvoiceType())){  //0:蓝票 1：红票
            PInvoiceBlue invoiceBlue = pInvoiceBlueService.getByKey(requestJson.getReceiptGuid());
            if (invoiceBlue == null){
                    retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS,"receiptGuid");
            }else {
                if (invoiceBlue.getInvoiceNo().equals(requestJson.getInvoiceNo())&&invoiceBlue.getInvoiceCode().equals(requestJson.getInvoiceCode())) {
                    response = callOut_invoiceQueryOutController.invoiceBlueQueryOut(invoiceBlue);
                    retJson = invQuery(response,retJson);
                }else {
                    retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS,"invoiceNo/invoiceCode");
                }
            }
        }else {
            PInvoiceRed invoiceRed = pInvoiceRedService.getByKey(requestJson.getReceiptGuid());
            if (invoiceRed == null){
                retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS,"receiptGuid");
            }else {
                if (invoiceRed.getInvoiceNo().equals(requestJson.getInvoiceNo())&&invoiceRed.getInvoiceCode().equals(requestJson.getInvoiceCode())) {
                    response = callOut_invoiceQueryOutController.invoiceRedQueryOut(invoiceRed);
                    retJson = invQuery(response,retJson);
                }else {
                    retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS,"invoiceNo/invoiceCode");
                }
            }
        }
            if(response == null){
                retJson = new ResponseJson(ErrorInfoEnum.FAIL_QUERY,"发票"+requestJson.getInvoiceNo());
            }
        return retJson.toString();
    }

    /***
     * 查询公共方法
     */
    public ResponseJson invQuery(InvoiceQueryResponse response ,ResponseJson retJson){
            JSONArray  invoiceDetailsArray = new JSONArray();
            List<InvoiceMainInfo> invoiceList = response.getInvoiceList();
            for (InvoiceMainInfo invoiceMainInfo:
                    invoiceList) {
                retJson.addBody("invoiceTypeCode",invoiceMainInfo.getInvoiceTypeCode());          // 发票种类编码   004:增值税专用发票， 007:增值税普通发票， 026：增值税电子发票， 025：增值税卷式发票
                retJson.addBody("invoiceTerminalCode",invoiceMainInfo.getInvoiceTerminalCode()); // 开票点编码
                retJson.addBody("drawer",invoiceMainInfo.getDrawer());                          // 开票人
                retJson.addBody("checker",invoiceMainInfo.getChecker());                       // 复核人
                retJson.addBody("payee",invoiceMainInfo.getPayee());                            // 收款人
                retJson.addBody("invoiceType",invoiceMainInfo.getInvoiceType());                // 开票类型    0:正数发票（蓝票） 1：负数发票（红票）
                retJson.addBody("invoiceCode",invoiceMainInfo.getInvoiceCode());                // 发票代码
                retJson.addBody("invoiceNo",invoiceMainInfo.getInvoiceNo());                    // 发票号码
                retJson.addBody("invoiceDate",invoiceMainInfo.getInvoiceDate());                // 开票日期
                retJson.addBody("invoiceQrCode",invoiceMainInfo.getInvoiceQrCode());            // 二维码
                retJson.addBody("buyerName",invoiceMainInfo.getBuyerName());                    // 购方单位名称
                retJson.addBody("buyerTaxNo",invoiceMainInfo.getBuyerTaxNo());                  // 购方纳税人识别号
                retJson.addBody("buyerAddressPhone",invoiceMainInfo.getBuyerAddressPhone());    // 购方地址及电话
                retJson.addBody("buyerBankAccount",invoiceMainInfo.getBuyerBankAccount());      // 购方开户行及账号
                retJson.addBody("buyerEmail",invoiceMainInfo.getBuyerEmail());                  // 购方客户邮箱
                retJson.addBody("buyerPhone",invoiceMainInfo.getBuyerPhone());                  // 购方客户电话
                retJson.addBody("formatFileUrl",invoiceMainInfo.getFormatFileUrl());            // 	版式文件下载地址
                retJson.addBody("invoiceStatus",invoiceMainInfo.getInvoiceStatus());              // 发票状态  00开具成功 02空白发票作废 03:已开发票作废
                retJson.addBody("invoiceSignMark",invoiceMainInfo.getInvoiceSignMark());          // 签名标志  Y：已签名；N：未签名
                retJson.addBody("invoiceUploadMark",invoiceMainInfo.getInvoiceUploadMark());      // 上传标志  Y：已上传；N：未上传
                retJson.addBody("invoiceCheckMark",invoiceMainInfo.getInvoiceCheckMark());        // 验签标志  Y：已验签；N：未验签
                retJson.addBody("invoiceListMark",invoiceMainInfo.getInvoiceListMark());          // 清单标志  0：无清单 1：带清单
                retJson.addBody("redInfoNo",invoiceMainInfo.getRedInfoNo());                      // 红字信息表编号
                retJson.addBody("notificationNo",invoiceMainInfo.getNotificationNo());            // 通知单编号
                retJson.addBody("originalInvoiceCode",invoiceMainInfo.getOriginalInvoiceCode());  // 原发票代码
                retJson.addBody("originalInvoiceNo",invoiceMainInfo.getOriginalInvoiceNo());      // 原发票号码
                retJson.addBody("deductibleAmount",invoiceMainInfo.getDeductibleAmount());        // 扣除额
                retJson.addBody("invoiceTotalPrice",invoiceMainInfo.getInvoiceTotalPrice());      // 合计金额
                retJson.addBody("invoiceTotalTax",invoiceMainInfo.getInvoiceTotalTax());           // 合计税额
                retJson.addBody("invoiceTotalPriceTax",invoiceMainInfo.getInvoiceTotalPriceTax());// 价税合计
                JSONObject json = new JSONObject();
                for (InvoiceDetails InvoiceDetails : invoiceMainInfo.getInvoiceDetailsList()) {
                    json.put("goodsLineNo",InvoiceDetails.getGoodsLineNo());           // 行号
                    json.put("goodsLineNature",InvoiceDetails.getGoodsLineNature());   //发票行性质  0：正常行 1：折扣行 2：被折扣行
                    json.put("goodsCode",InvoiceDetails.getGoodsCode());               //商品编码
                    json.put("goodsExtendCode",InvoiceDetails.getGoodsExtendCode());   //自行编码
                    json.put("goodsName",InvoiceDetails.getGoodsName());               //商品名称
                    json.put("goodsTaxItem",InvoiceDetails.getGoodsTaxItem());         //商品税目
                    json.put("goodsQuantity",InvoiceDetails.getGoodsQuantity());       //商品数量
                    json.put("goodsPrice",InvoiceDetails.getGoodsPrice());             //单价
                    json.put("goodsTotalPrice",InvoiceDetails.getGoodsTotalPrice());   //金额
                    json.put("goodsTotalTax",InvoiceDetails.getGoodsTotalTax());       //税额
                    json.put("goodsTaxRate",InvoiceDetails.getGoodsTaxRate());         //税率
                    json.put("priceTaxMark",InvoiceDetails.getPriceTaxMark());         //含税标志   0：不含税 1：含税
                    json.put("vatSpecialManagement",InvoiceDetails.getVatSpecialManagement());  //增值税特殊管理
                    json.put("freeTaxMark",InvoiceDetails.getFreeTaxMark());           //零税率标识   空代表无 1 出口免税和其他免税优惠政策 2 不征增值税 3 普通零税率
                    json.put("preferentialMark",InvoiceDetails.getPreferentialMark()); //是否使用优惠政策   0:未使用，1:使用
                    invoiceDetailsArray.add(json);
                }
                retJson.addBody("invoiceDetailsList",invoiceDetailsArray);
            }
        return retJson;
    }

}
